package com.manyan.demo.aspect;

import com.manyan.demo.an.DataSource;
import com.manyan.demo.config.DataSourceType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 根据注解获取
 */
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Before("@annotation(dataSource)")//拦截我们的注解
    public void changeDataSource(JoinPoint point, DataSource dataSource) throws Throwable {
        String value = dataSource.value();
        if (value.equals("primary")) {
            DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Primary);
        } else if (value.equals("secondary")) {
            DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Secondary);
        } else {
            DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Primary);/*默认使用主数据库*/
        }

    }

    @After("@annotation(dataSource)") //清除数据源的配置
    public void restoreDataSource(JoinPoint point, DataSource dataSource) {
        DataSourceType.clearDataBaseType();


    }
}